package com.fuqi.android.zhongcai.business.shuig.view.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Color;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.fuqi.android.zhongcai.R;
import com.fuqi.android.zhongcai.base.request.api.PushImgApi;
import com.fuqi.android.zhongcai.base.request.result.PushResult;
import com.fuqi.android.zhongcai.base.view.activity.BaseActivity;
import com.fuqi.android.zhongcai.base.view.widget.CustomProgress;
import com.fuqi.android.zhongcai.base.view.widget.wheelwidget.OptionsPickerView;
import com.fuqi.android.zhongcai.base.view.widget.wheelwidget.TimePickerView;
import com.fuqi.android.zhongcai.business.shuig.OrderDict;
import com.fuqi.android.zhongcai.business.shuig.request.api.OrderHandleApi;
import com.fuqi.android.zhongcai.business.shuig.request.result.OrderHandleResult;
import com.fuqi.android.zhongcai.business.shuig.view.widget.CJRow.ARResponse;
import com.fuqi.android.zhongcai.sql.Dic;
import com.fuqi.android.zhongcai.sql.dao.SQLDao;
import com.fuqi.android.zhongcai.utils.ActivityUtils;
import com.fuqi.android.zhongcai.utils.DateUtil;
import com.fuqi.android.zhongcai.utils.FileUtil;
import com.fuqi.android.zhongcai.utils.FormImgsUtils;
import com.fuqi.android.zhongcai.utils.ImageUtils;
import com.fuqi.android.zhongcai.utils.LogUtils;
import com.fuqi.android.zhongcai.utils.RegexUtil;
import com.fuqi.framework.network.code.HandleCode;
import com.fuqi.framework.network.http.RequestManager;
import com.fuqi.framework.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerActivity;
import cn.bingoogolapple.photopicker.activity.BGAPhotoPickerPreviewActivity;
import cn.bingoogolapple.photopicker.widget.BGASortableNinePhotoLayout;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;

public class ShuiGCannotInstallActivity extends BaseActivity implements EasyPermissions.PermissionCallbacks,BGASortableNinePhotoLayout.Delegate, FormImgsUtils.UploadCallback {
    @Bind(R.id.tv_date)
    TextView mTvDate;
    @Bind(R.id.tv_reason)
    TextView mTvReason;
    @Bind(R.id.et_remark)
    EditText mEtRemark;
    @Bind(R.id.activity_discover_invest_publish_picture_iv)
    ImageView mIvPub;

    private BGASortableNinePhotoLayout ninePhotoLayout;
    //    选择头像请求码
    private static final int REQUEST_CODE_PERMISSION_PHOTO_PICKER = 1;
    private static final int REQUEST_CODE_CHOOSE_PHOTO = 1;
    private static final int REQUEST_CODE_PHOTO_PREVIEW = 2;
//    private ArrayList<String> selectedPhotos = new ArrayList<>();
    private static final int MAX_PHOTO_COUNT = 9;
    private ArrayList<String> netPhotos = new ArrayList<>();

    TimePickerView pvTime;
    OptionsPickerView pvOptions;

    ARResponse response;
    String sDate;
    ArrayList<Dic> options1Items = new ArrayList<>();

    @OnClick({R.id.tv_date,R.id.tv_reason,R.id.btn_submit, R.id.activity_discover_invest_publish_picture_iv})
    public void onClick(View v){
        switch (v.getId()) {
            case R.id.tv_reason:
                pvOptions = new OptionsPickerView(this);
                options1Items.clear();
                List<Dic> dics = SQLDao.getInstance(getApplicationContext()).selectDNSY(OrderDict.DNSYType.SJ_BKAZYY);
                /*options1Items.add("槽未开洞未打");
                options1Items.add("客户临时更换品牌");
                options1Items.add("小区禁止噪音施工");
                options1Items.add("其他");*/
                options1Items.addAll(dics);
                pvOptions.setPicker(options1Items);

                pvOptions.setSelectOptions(1, 0, 0);
                pvOptions.setCyclic(false);
                pvOptions.setCancelable(true);
                //时间选择后回调
                pvOptions.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

                    @Override
                    public void onOptionsSelect(int options1, int option2, int options3) {
                        if(options1Items.size() <= options1)       return ;
                        mTvReason.setText(options1Items.get(options1).toString());
                        mTvReason.setTag(options1Items.get(options1).getPbianma());
                        mTvReason.setTextColor(Color.parseColor("#444444"));
                    }
                });
                pvOptions.show();
                break;
            case R.id.tv_date:
                pvTime = new TimePickerView(this, TimePickerView.Type.YEAR_MONTH_DAY);
                pvTime.setTime(new Date());
                pvTime.setCyclic(false);
                pvTime.setCancelable(true);
                //时间选择后回调
                pvTime.setOnTimeSelectListener(new TimePickerView.OnTimeSelectListener() {

                    @Override
                    public void onTimeSelect(Date date) {
                        sDate = DateUtil.getStringByFormat(date,DateUtil.dateFormatYMD);
                        mTvDate.setText(sDate);
                    }
                });
                pvTime.show();
                break;
            case R.id.activity_discover_invest_publish_picture_iv:
                choicePhotoWrapper();
                break;
            case R.id.btn_submit:
                netPhotos = ninePhotoLayout.getData();
                if(prepare())
                    doUpload();
                break;
        }
    }

    Response.Listener<OrderHandleResult> respOrderHandleListener = new Response.Listener<OrderHandleResult>() {

        @Override
        public void onResponse(OrderHandleResult response) {
            CustomProgress.close();
            if (HandleCode.requestSuccess()) {
                ActivityUtils.toast("不可安装提交成功。");
                finish();
                Log.i("juner", "juner respOrderHandleListener response : ");
            } else {
            }
        }
    };

    Response.Listener<PushResult> respWorkersListener = new Response.Listener<PushResult>() {

        @Override
        public void onResponse(PushResult response) {
            CustomProgress.close();
            if (HandleCode.requestSuccess()) {
                netPhotos.addAll(StringUtil.getList(response.getPath(),","));
//                if(netPhotos.size() == selectedPhotos.size()) {
                    doPublish();
//                }
                Log.i("juner", "juner respWorkersListener response : " + response.getPath());
            } else {
            }
        }
    };


    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            CustomProgress.close();
            FileUtil.clearDir(FileUtil.getTempFile());
            Log.i("juner", "juner  error.getMessage(): " + error.getMessage());

        }
    };

    boolean prepare(){
        if(!RegexUtil.checkNotNull(mTvReason.getText().toString())){
            ActivityUtils.toast("请选择原因。");
            return false;
        }else if(!RegexUtil.checkNotNull(sDate)){
            ActivityUtils.toast("请选择时间。");
            return false;
        }else if(netPhotos.size() == 0){
            ActivityUtils.toast("请上传图片。");
            return false;
        }
        return true;
    }

    private void doPublish(){
        if(response != null) {
            response.update("INSTALL_DATE", sDate);
            response.update("REFUSE_REASON", mTvReason.getTag().toString());
            response.update("REFUSE_REMARK", mEtRemark.getText().toString());
            response.update("ORDER_STATUS", OrderDict.StatusType.DDZT_BKAZ);
            if(netPhotos != null && netPhotos.size() >0)
                response.update("refuseFiles", StringUtil.getListString(netPhotos)); // 不可安装图片路径，多个路径中间用逗号分隔
            RequestManager.getInstance().call(new OrderHandleApi(
                    new OrderHandleApi.OrderHandleParams(response.getDataWithMap()), respOrderHandleListener, errorListener));
            Log.i("response : ", response.toString());
            CustomProgress.show(ShuiGCannotInstallActivity.this,"正在提交...",true,null);
        }
    }

    private void doUpload(){
        ActivityUtils.toast("图片处理中...");
        ninePhotoLayout.postDelayed(new Runnable() {
            @Override
            public void run() {
                List<File> files = ImageUtils.makePaths2ImgFileList(netPhotos);
                netPhotos.clear();
                CustomProgress.show(ShuiGCannotInstallActivity.this, "正在上传...", true, null);
                PushImgApi p = new PushImgApi(respWorkersListener, errorListener, "files", files, null);
                RequestManager.getInstance().call(p);
            }
        },100);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQUEST_CODE_CHOOSE_PHOTO) {
            ninePhotoLayout.setData(BGAPhotoPickerActivity.getSelectedImages(data));
            mIvPub.setVisibility(View.GONE);
        } else if (requestCode == REQUEST_CODE_PHOTO_PREVIEW) {
            ninePhotoLayout.setData(BGAPhotoPickerPreviewActivity.getSelectedImages(data));
        }
    }



    @Override
    public void initView() {
        titleBar.setTitle("不可安装");
        ninePhotoLayout = (BGASortableNinePhotoLayout) findViewById(R.id.activity_discover_invest_publish_nine_photo);
        ninePhotoLayout.init(ShuiGCannotInstallActivity.this);
        ninePhotoLayout.setDelegate(ShuiGCannotInstallActivity.this);
    }


    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        response = new ARResponse(getIntent().getStringExtra("response"));
    }

    @Override
    public boolean hasTitleBar() {
        return true;
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_cannot_install;
    }


    @AfterPermissionGranted(REQUEST_CODE_PERMISSION_PHOTO_PICKER)
    private void choicePhotoWrapper() {
        String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (EasyPermissions.hasPermissions(this, perms)) {
            // 拍照后照片的存放目录，改成你自己拍照后要存放照片的目录。如果不传递该参数的话就没有拍照功能
            File takePhotoDir = new File(Environment.getExternalStorageDirectory(), "ZhongCDownload");

            startActivityForResult(BGAPhotoPickerActivity.newIntent(this, takePhotoDir, 9, ninePhotoLayout.getData()), REQUEST_CODE_CHOOSE_PHOTO);
        } else {
            EasyPermissions.requestPermissions(this, "图片选择需要以下权限:\n\n1.访问设备上的照片", REQUEST_CODE_PERMISSION_PHOTO_PICKER, perms);
        }
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
        if (requestCode == REQUEST_CODE_PERMISSION_PHOTO_PICKER) {
            Toast.makeText(this, "您拒绝了「图片选择」所需要的相关权限!", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClickAddNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, ArrayList<String> models) {
        choicePhotoWrapper();
    }

    @Override
    public void onClickDeleteNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        ninePhotoLayout.removeItem(position);
    }

    @Override
    public void onClickNinePhotoItem(BGASortableNinePhotoLayout sortableNinePhotoLayout, View view, int position, String model, ArrayList<String> models) {
        startActivityForResult(BGAPhotoPickerPreviewActivity.newIntent(this, MAX_PHOTO_COUNT, models, models, position, false), REQUEST_CODE_PHOTO_PREVIEW);
    }

    @Override
    public void onUploadStart() {

    }

    @Override
    public void onUploadFinish() {

    }

    @Override
    public void onUploadSuccess(String avatarUrl) {
        LogUtils.i("comment upload img success!");
    }

    @Override
    public void onUploadError() {

    }
}
